package com.spring.app.controller;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.Future;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.spring.app.domain.ItemData;
import com.spring.app.domain.TransactionFile;
import com.spring.app.service.BuyerService;
import com.spring.app.service.EmailSenderService;
import com.spring.app.service.ProductsService;
import com.spring.app.util.ExcelFileUtil;

//import com.spring.app.service.UserService;

/**
 * Handles requests for the application home page.
 */
@Controller
@PropertySource({"classpath:/properties/mail.properties"})
public class HomeController {

	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
	@Autowired
	private ProductsService productsService;
	@Autowired
	private ExcelFileUtil excelFileUtil;
	@Autowired
	private BuyerService buyerService;
	@Autowired
	private EmailSenderService emailSenderService;
	@Autowired
	Environment environment;
	@Autowired
	JavaMailSender javaMailSender;

	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String home(Locale locale, Model model) {
		logger.info("Welcome home! The client locale is {}.", locale);

		Date date = new Date();
		DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);

		String formattedDate = dateFormat.format(date);

		model.addAttribute("serverTime", formattedDate );

		return "searchProducts";
	}

	@RequestMapping(value = "/addItemFromFile/{path}", method = RequestMethod.GET)
	@ResponseBody
	public String addItemFromFile(@PathVariable String path,  HttpServletResponse response, HttpServletRequest request) throws IOException {
		File f = new File("C:/ebay/ItemList.txt");
		BufferedReader br = new BufferedReader(new FileReader(f));
		String line;
		while ((line = br.readLine()) != null) {
		   System.out.println(line);
		   ItemData item = new ItemData();
			item.setItemCode(line.split(",")[2]);
			item.setItemnamew(line.split(",")[1]);
			item = productsService.save(item);
		}
		br.close();
		return "done";
	}

	@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
	@ResponseBody
	public String uploadFiles(@RequestParam("excel") MultipartFile excel,HttpServletResponse response, HttpServletRequest request) {

		try { 
			if(!(excel.getOriginalFilename().endsWith(".xls") || excel.getOriginalFilename().endsWith(".xlsx")
					|| excel.getOriginalFilename().endsWith(".csv"))){
				return " Not a valied Excel File";
			}

			String fileName=buyerService.getInventoryFileName(excel.getOriginalFilename());
			File f=new File("C:\\ebay",fileName);
			f.createNewFile();
			FileCopyUtils.copy(excel.getBytes(), new FileOutputStream(f));
			System.out.println(fileName);	
			TransactionFile transactionFile=new TransactionFile();
			transactionFile.setFileName(fileName);
			transactionFile.setFilePath("C:\\ebay\\"+excel.getOriginalFilename());
			transactionFile.setImportDate(new Timestamp(Calendar.getInstance().getTime().getTime()));

			transactionFile=buyerService.saveTransactionFile(transactionFile);



			Future<Map> buyerData=buyerService.readExcel(excel.getOriginalFilename());
			buyerData.get().put("fileName", fileName);
			buyerService.save((List)buyerData.get().get("buyerDataList"),transactionFile);

			return "File Uploaded Succesfully";
		} catch (Exception e) {
			e.printStackTrace();
			return "Unable to upload the file.Please try again later";
		} 

	}



	@RequestMapping(value="/generateLabel",method=RequestMethod.POST)
	@ResponseBody
	public String generateLabel(HttpServletRequest request){
		try{
			String file=request.getParameter("file");

			Future<Map> buyerData=buyerService.readExcel(file);
			File afile = new File("C:\\ebay\\"+file);
			if(afile.renameTo(new File("C:\\ebay\\archives\\" + afile.getName()))){
				System.out.println("File is archived successfully!");
			}else{
				System.out.println("File to archive!");
			}


			buyerData.get().put("fileName", file);
			buyerService.generatePostageLabel(buyerData.get());
			if(file.endsWith("xls"))
				file+="_xls";

			System.out.println(environment.getProperty("mail.postagelabels"));
			Future<Boolean> status=emailSenderService.sendEmailWithAttachments(environment.getProperty("mail.postagelabels"),"Please find the attachments",
					"Postage Labels","C:\\ebay\\"+file.substring(0,file.lastIndexOf("."))+"_postageLabel.xls", (String[])null);

			if(status.get().equals(true)) {
				return "Email has been dispatched ";
			}
		}catch(Exception e){
			return "Unable to send Mail";
		}
		return "Unable to send mail";
	}


	@ResponseBody
	@RequestMapping(value="/showUploadedFiles",method=RequestMethod.GET)
	public String showAllFiles(){


		return buyerService.getAllFromTransactionFile();
	}


	@RequestMapping(method = RequestMethod.POST, value = "/addItemDataContent")
	public  @ResponseBody ItemData addItemDataContent(
			@RequestBody ItemData item,
			HttpServletResponse response, HttpServletRequest request) {

		//item.setItemId(1l);
		//item.setItemCode("ssss");
		//item.setItemnamew("dbddg");

		if(item !=null) {
			//item = userService.getUserById(item);
		}
		return item;
	}

	@RequestMapping(value = "/AddItemData/{itemName}/{itemCode}/{itemId}", method = RequestMethod.GET)
	@ResponseBody
	public String AddItemData(@PathVariable String itemName, @PathVariable String itemCode, @PathVariable Long itemId ,HttpServletResponse response, HttpServletRequest request) {
		ItemData item = new ItemData();
		if(itemId !=null && itemId !=0){ //Update same row
			item.setItemId(itemId);
		}
		item.setItemCode(itemCode);
		item.setItemnamew(itemName);
		item = productsService.save(item);
		return item.getItemId().toString();
	}

	@RequestMapping(value = "/itemDataList", method = RequestMethod.GET)
	@ResponseBody
	public List<ItemData> ItemDataList(HttpServletResponse response, HttpServletRequest request) {
		List<ItemData> list = productsService.getItemDataList();
		return list;
	}

	@RequestMapping(value = "/deleteItem/{itemId}", method = RequestMethod.GET)
	@ResponseBody
	public int deleteItem(@PathVariable Long itemId, HttpServletResponse response, HttpServletRequest request) {
		productsService.deleteItem(itemId);
		return 1;
	}

	@RequestMapping(value = "/searchItemsData/{searchKeyword}", method = RequestMethod.GET)
	@ResponseBody
	public List<ItemData> searchItemsData(@PathVariable String searchKeyword, HttpServletResponse response, HttpServletRequest request) {
		List<ItemData> list = productsService.getSearchItemsbyKeyword(searchKeyword);
		return list;
	}


}
